import { App } from 'vue'
import axios, { AxiosError } from 'axios'
import { parseJSON } from '@lhy-assist/utils'

export default {
  install(app: App) {
    axios.interceptors.response.use(
      response => {
        // 下载blob文件失败时，解析出失败内容并转为异常抛出
        if (response.data instanceof Blob && /^application\/json$/i.test(response.data.type)) {
          return response.data.text().then(text => {
            const json = parseJSON(text)
            response.data = json
            throw new AxiosError(
              json.msg || '下载失败',
              String(json.code || 500),
              response.config,
              response.request,
              response
            )
          })
        }

        return response
      },
      (err: AxiosError<any>) => {
        if (typeof err.response?.data === 'string') {
          err.response.data = parseJSON(err.response.data)
        }
        return Promise.reject(err)
      }
    )
  },
}
